package HibernateOrederManagement.app;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import HibernateOrderManagerment.bean.User;
import HibernateOrderManagerment.bean.UserStatus;

public class UserDao {
	private Session session;
	public UserDao(Session session){
		this.session=session;
	}
	public List<User> list(){
		Query<User> query=session.createQuery("from User",User.class);
		return query.getResultList();
	}
	public User getUserById(long id) {
		return session.get(User.class, id);
	}
	public User getByName(String name){
		Query<User> query =session.createQuery("from User where name=:name",User.class);
		query.setParameter("name", name);
		return query.getSingleResult();
	}
	public User getByAddress(String address){
		Query<User> query =session.createQuery("from User where address=:address",User.class);
		query.setParameter("address", address);
		return query.getSingleResult();
	}
	public User getByPhone(String phone){
		Query<User> query =session.createQuery("from User where phone=:phone",User.class);
		query.setParameter("phone", phone);
		return query.getSingleResult();
	}
	public User getByUserStatusId(long id){
		UserStatusDao dao =new UserStatusDao(session);
		UserStatus userStatus =dao.getUserStatusById(id);
		Query<User> query =session.createQuery("from User where userStatus=:userStatus",User.class);
		query.setParameter("userStatus", userStatus);
		return query.getSingleResult();
	}
	public void insert(User user) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(user);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(User user){
		Transaction tx = session.beginTransaction();
		try {

			session.update(user);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public void delete(User user){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(user);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}


}
